#include "compile_run.hpp"
#include "../comm/httplib.h"
using namespace ns_compile_and_run;
using namespace httplib;

void Usage(std::string proc)
{
    std::cout << "Usage: " << proc << " port" << std::endl;
    std::cout << "Example: " << proc << " 8080" << std::endl;
}

inline void listenForQuitCommand(Server &svr) {
    std::string input;
    while (true) {
        std::getline(std::cin, input);
        if (input == "quit" || input == "q") {
            std::cout << "Server is stopping..." << std::endl;
            svr.stop();
            break;
        }
    }
}

int main(int argc, char* argv[]) {   
    // 根据提供的编译运行服务，打包成网络功能
    if (argc != 2) {
        Usage(argv[0]);
        return 1;
    }

    Server svr;
    
    svr.Post("/compile_and_run", [](const Request& req, Response& resp) {
        std::string in_json = req.body;
        std::string out_json;
        if (!in_json.empty()) {
            CompileAndRun::Start(in_json, &out_json);
            resp.set_content(out_json, "application/json;charset=utf-8");
        }
    });

    std::thread inputThread(&listenForQuitCommand, std::ref(svr));  // 使用 std::ref 传递引用

    // svr.set_base_dir("../oj_server/wwwRoot");
    std::cout << "listen..." << std::endl;
    svr.listen("0.0.0.0", atoi(argv[1]));

    // 等待输入线程结束
    inputThread.join();

    return 0;
}